package com.my.jvm.init;

import lombok.extern.slf4j.Slf4j;

/**
 * 执行顺序：静态代码块 -> 普通代码块 -> 构造函数；如果有多个代码块，则根据顺序依次执行。
 *
 * @author: marshal
 * @date: 2023-07-19 10:31 AM
 */
@Slf4j
public class InitialBlock {
    private String name;
    private int age;

    private static String static_str;
    private static final String CONSTANT = "HELLO";

    /**
     * final修饰的变量必须在声明时就显式赋值或者在构造器里赋值
     */
    private final int a; // 在构造器赋值

    private final int b = 20; // 声明时显式赋值

    // 静态代码块
    static {
        static_str = "This is static variable";
        log.debug("This is static initial block!");
    }

    // 普通代码块
    {
        name = "Jack";
        log.debug("This is first initial block!");
    }

    {
        name = "Tom";
        log.debug("This is second initial block!");
    }

    /**
     * 构造函数
     */
    public InitialBlock() {
        a = 10;
        log.debug("This is constructor!");
    }

    public static void main(String[] args) {
        InitialBlock block = new InitialBlock();
        log.debug("block = {}", block);
        log.debug("static_str = {}", static_str);
        log.debug("CONSTANT = {}", CONSTANT);
    }


    @Override
    public String toString() {
        return "InitialBlock{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
